import 'package:ball_lion/base/base_controller.dart';
import 'package:ball_lion/module/home/live_logic.dart';
import 'package:ball_lion/service/resource_service.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/live/live_list_page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/home/news_list_logic.dart';
import 'package:ball_lion/entity/home/news_classfier_entity.dart';
import 'package:ball_lion/server/api/home_api.dart';
import 'package:ball_lion/server/api/live_api.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/module/home/home_channel_filter_page.dart';
import 'package:ball_lion/module/home/news_list_view.dart';

class HomeLogic extends BaseController with GetTickerProviderStateMixin {
  TabController? tabController;
  int _index = 0;
  int unreadCount = 0;
  List<Widget> pages = [];
  bool _loading = true;
  bool hasLive = false;
  bool highlightRed = false;
  List<NewsClassfierEntity>? classes;

  int get index => _index;

  bool get loading => _loading;

  set loading(bool value) {
    _loading = value;
    update();
  }

  set index(int value) {
    _index = value;
    update();
  }

  @override
  void onReady() {
    getClasses();
    super.onReady();
  }

  Future doRefresh() async {
    if (classes![index].id == "app_live") {
      Get.find<LiveLogic>().doRefresh();
    } else {
      Get.find<NewsListLogic>(tag: classes![index].id).doRefresh();
    }
  }

  getClasses({String? initId}) async {
    String defaultId =
        Get.find<ResourceService>().homeDefaultTab?.content ?? "toutiao";
    bool equal = true;
    final l = await HomeApi.getHomeClasses(!User.isLogin);
    var newIndex = index;
    if (classes == null) {
      classes = l;
      newIndex = classes?.indexWhere((element) => element.id == defaultId) ?? 0;
      if (newIndex == -1) newIndex = 0;
      index = newIndex;
    } else {
      //是否有修改频道
      if (l.length != classes!.length) {
        equal = false;
      } else {
        for (int i = 0; i < l.length; i++) {
          if (l[i].id != classes![i].id) {
            equal = false;
          }
        }
      }
      classes = l;
      if (index > (classes?.length ?? 1) - 1) {
        newIndex =
            classes?.indexWhere((element) => element.id == defaultId) ?? 0;
        if (newIndex == -1) newIndex = 0;
        index = newIndex;
      }
      if (classes?.indexWhere((e) => e.id == initId) != -1) {
        newIndex = classes!.indexWhere((e) => e.id == initId);
      }
      if (equal) {
        if (newIndex != index) {
          tabController?.animateTo(newIndex);
        }
        return;
      }
    }
    pages = [];
    pages.addAll(List.generate(classes?.length ?? 0, (index) {
      if (classes![index].id == "app_live") {
        return const LiveListPage();
      } else {
        return NewsListView(
            id: classes![index].id, key: Key("${classes![index].id}$index"));
      }
    }));
    tabController?.dispose();
    tabController = TabController(
        length: classes!.length, vsync: this, initialIndex: newIndex);
    tabController!.addListener(() {
      index = tabController!.index;
      highlightRed = (classes![index].id == "qssyxijia");
      // classes![index].id != "app_live"
      //     ? Utils.onEvent('sypdzx', params: {'sypdzx': classes![index].name})
      //     : Utils.onEvent('zbfl', params: {'zbfl': 0});
    });
    update();
  }

  Future getLive() async {
    var list = await LiveApi.getLiveList(0);
    hasLive = list.where((element) => element.status == 1).toList().hasValue;
    update();
  }

  onTapFilter() {
    User.needLogin(() async {
      var result = await Get.bottomSheet(const HomeChannelFilterPage(),
          isScrollControlled: true, enableDrag: false, ignoreSafeArea: false);
      getClasses(initId: result);
    });
  }

  void toIndex(String id) {
    var result = classes!.indexWhere((element) => element.id == id);
    if (result >= 0) tabController?.animateTo(result);
  }

  Future getMsgCount() async {
    if (User.isLogin) {
      var c = await UserApi.getSystemUnreadCount();
      var o = await UserApi.getInterUnreadCount();
      unreadCount = (c ?? 0) + (o ?? 0);
    } else {
      unreadCount = 0;
    }
    update();
  }

  @override
  void getRefresh() {
    getClasses();
    getMsgCount();
    super.getRefresh();
  }
}
